package com.taptech.doufu.ui.view.personalcenter;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.taptech.doufu.util.ListViewUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.DFKeepActivity;
import com.taptech.doufu.bean.MineAbstractBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.view.drawcircle.MyRecyclerView;
import com.taptech.doufu.ui.view.drawcircle.RecyclerViewAdapterAsListView;
import com.taptech.doufu.event.EventBusCollectUnRead;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.ui.viewholder.personalcenter.MessageViewHolderFactory;
import com.taptech.doufu.services.personalcenter.PersonalInfoService;
import com.taptech.doufu.ui.adapter.personalcenter.CollectPopAdapter;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.net.httputils.HttpUtil;
import com.taptech.doufu.ui.view.WaitDialog;
import com.taptech.doufu.ui.viewholder.personalcenter.PersonalNoteViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by longsiyang on 15/11/20.
 */
public class NewMyCollectView implements View.OnClickListener, HttpResponseListener
{

    Context mContext;
    MyRecyclerView listView;
    RecyclerViewAdapterAsListView adapter;
    private String last = "";
    private PopupWindow mPopupWindow;
    private ListView mPopListView;
    private ImageView mCurPageImg;
    private View typeCollectBtn;
    private TextView typeTextTitle;
    private int typeCollectedMode;
    private MessageViewHolderFactory viewHolderFactory;

    private final int SEL_COLLECT_MODEL_ALL = 0;
    private final int SEL_COLLECT_MODEL_NOVEL = 1;
    private final int SEL_COLLECT_MODEL_CARTOON = 2;
    private final int SEL_COLLECT_MODEL_NOTE = 3;
    private final int SEL_COLLECT_MODEL_SWEEP = 4;


    public static final int DEL_COLLECT_ITEM_COMMAND = 1000;

    private WaitDialog mWaitDialog;

    private boolean hasMoreContent = false;
    private boolean isLoadingCollect = false;
    // 收藏日常数据
    private List<MineAbstractBean> mDataList;
    private int order;

    public NewMyCollectView(View view, Context context)
    {
        this.mContext = context;
        mDataList = new ArrayList<>();
        viewHolderFactory = new MessageViewHolderFactory();
        initView(view);
    }

    public NewMyCollectView(View view, Context context,int order)
    {
        this.mContext = context;
        mDataList = new ArrayList<>();
        viewHolderFactory = new MessageViewHolderFactory();
        this.order = order;
        initView(view);
    }

    private void initView(View view)
    {
        listView = (MyRecyclerView) view.findViewById(R.id.personal_my_collect_layout_list);
        RecyclerView.LayoutManager manager = new LinearLayoutManager(mContext);
        listView.setLayoutManager(manager);
        adapter = new RecyclerViewAdapterAsListView(mContext, mDataList, handler);

        listView.setAdapter(adapter);
        listView.setLoadMoreEnable(true);
        listView.setOnScrollToBottomListener(new MyRecyclerView.OnScrollToBottomListener()
        {
            @Override
            public void loadMore()
            {
                loadMoreData();
            }
        });

        typeCollectBtn = view.findViewById(R.id.personal_my_collect_layout_top);
        typeCollectBtn.setOnClickListener(this);
        typeTextTitle = (TextView) view.findViewById(R.id.personal_my_collect_layout_page);
        typeCollectedMode = SEL_COLLECT_MODEL_ALL;
        mCurPageImg = (ImageView) view.findViewById(R.id.personal_my_collect_layout_img);
        loadDataByType(typeCollectedMode,order,false);
        makePopWindow();

    }


    public void orderChange(int order) {
        if (this.order != order) {
            this.order = order;
            last = "";
            loadDataByType(typeCollectedMode,order,false);
        }
    }


    private void loadDataByType(int position,int order,boolean fromUser)
    {
        isLoadingCollect = true;
        hasMoreContent = true;
        switch (position)
        {
            case SEL_COLLECT_MODEL_ALL:
                if (fromUser) {
                    TMAnalysis.event(mContext, "COLLECT_SHOW_ALL");
                }
                PersonalInfoService.getInstance().loadCollect(this, last, SEL_COLLECT_MODEL_ALL, PersonalInfoService.HANDLE_LOAD_COLLECT_ALL,order);
                break;
            case SEL_COLLECT_MODEL_NOVEL:
                if (fromUser) {

                    TMAnalysis.event(mContext, "COLLECT_SHOW_NOVEL");
                }
                PersonalInfoService.getInstance().loadCollect(this, last, Constant.OBJECT_TYPE_NOVEL, PersonalInfoService.HANDLE_LOAD_COLLECT_NOVEL,order);
                break;
            case SEL_COLLECT_MODEL_SWEEP:
                if (fromUser) {

                    TMAnalysis.event(mContext, "COLLECT_SHOW_SWEEP");
                }
                PersonalInfoService.getInstance().loadCollect(this, last, Constant.OBJECT_TYPE_SWEEP, PersonalInfoService.HANDLE_LOAD_COLLECT_SWEEP,order);
                break;
            //个人日志请求
            case SEL_COLLECT_MODEL_NOTE:
                if (fromUser) {

                    TMAnalysis.event(mContext, "COLLECT_SHOW_NOTE");
                }
                PersonalInfoService.getInstance().loadCollect(this, last, Constant.OBJECT_TYPE_NOTE, PersonalInfoService.HANDLE_LOAD_COLLECT_NOTE,order);
                break;
            case SEL_COLLECT_MODEL_CARTOON:
                if (fromUser) {

                    TMAnalysis.event(mContext, "COLLECT_SHOW_CARTOON");
                }
                PersonalInfoService.getInstance().loadCollect(this, last , Constant.OBJECT_TYPE_CARTOON , PersonalInfoService.HANDLE_LOAD_COLLECT_CARTOON ,order);
                break;

            default:
                break;

        }
    }

    private synchronized void loadMoreData()
    {
        if (hasMoreContent)
        {

            loadDataByType(typeCollectedMode,order,false);
        }

    }


    @Override
    public void handleResponse(int handleType, HttpResponseObject response)
    {

        HttpUtil.setOnHandleHttpResponListener(mContext, handleType, response, new HttpUtil.HandleHttpResponListener()
        {
            @Override
            public void handleRespon(int handleType, JSONObject data)
            {
                if (data != null && mContext!=null)
                {

                    try
                    {
                        List<? extends MineAbstractBean> dataList = viewHolderFactory.getDataBeanFromJSONArray(data.getJSONArray("list"), PersonalNoteViewHolder.SPECIAL_TYPE_COLLECT);
                        if (dataList != null)
                        {
                            if (TextUtils.isEmpty(last)) {
                                mDataList.clear();
                            }
                            mDataList.addAll(dataList);
                            adapter.notifyDataSetChanged();
                            if (mContext!=null && mContext instanceof DFKeepActivity) {
                                EventBusCollectUnRead.clearUnRead();
                            }

                        }
                        String tempLast = data.getString("last");
                        if (tempLast == null ||tempLast.equals("null") || tempLast.equals(last) || tempLast.equals("1"))
                        {
                            hasMoreContent = false;
                            adapter.pullComplete(true);
                        }
                        last = tempLast;

                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                    }

                    switch (handleType)
                    {

                        case PersonalInfoService.HANDLE_LOAD_COLLECT_ALL:

                            break;

                        case PersonalInfoService.HANDLE_LOAD_COLLECT_TOPIC:

                            break;

                        case PersonalInfoService.HANDLE_LOAD_COLLECT_NOVEL:

                            break;
                        case PersonalInfoService.HANDLE_LOAD_COLLECT_SWEEP:

                            break;
                        case PersonalInfoService.HANDLE_LOAD_COLLECT_NOTE:

                            break;
                        case PersonalInfoService.HANDLE_LOAD_COLLECT_DRAW:

                            break;
                        case PersonalInfoService.HANDLE_LOAD_COLLECT_COS:

                            break;

                        default:
                            break;

                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.personal_my_collect_layout_top:
                showPopWindow();
                break;
        }

    }


    private void makePopWindow()
    {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.novel_des_comm_pop_list, null);
        mPopListView = (ListView) view.findViewById(R.id.novel_des_pop_list);
        mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //		mPopupWindow.setAnimationStyle(R.style.Animation_Top_Bottom);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener()
        {

            @Override
            public void onDismiss()
            {
                RotateAnimation animation = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                animation.setDuration(200);
                animation.setFillAfter(true);
                mCurPageImg.startAnimation(animation);
            }
        });
        final CollectPopAdapter popAdapter = new CollectPopAdapter(mContext, CollectPopAdapter.TYPE_COLLECT);
        mPopListView.setAdapter(popAdapter);
        mPopListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                if (typeCollectedMode == position)
                {
                    return;
                }
                if (mDataList != null)
                {
                    mDataList.clear();
                    adapter.pullComplete(false);
                    adapter.notifyDataSetChanged();

                }
                typeTextTitle.setText(popAdapter.getCollentTitle(position));
                popAdapter.setSelectPosition(position);
                mPopupWindow.dismiss();
                last = "";

                typeCollectedMode = position;
                loadDataByType(position,order,true);
            }
        });
    }

    public void showPopWindow()
    {
        if (mPopupWindow != null && !mPopupWindow.isShowing())
        {
            mPopupWindow.showAsDropDown(typeCollectBtn);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.update();

            RotateAnimation animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            animation.setDuration(200);
            animation.setFillAfter(true);
            mCurPageImg.startAnimation(animation);
        }

    }

    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            String id = "";
            String object_type = "";
            int position = 0;
            if (msg.what == DEL_COLLECT_ITEM_COMMAND)
            {
                id = msg.getData().getString("id");
                object_type = msg.getData().getString(Constant.OBJECT_TYPE);
                position = msg.getData().getInt("position");
                ListViewUtil.deleteItemCollect(mContext, mWaitDialog, mDataList, adapter, position, id, object_type);
            }
        }
    };
}
